<template>
  <view class="list-page">
    <!-- 搜索栏 -->
    <view class="list-search-bar">
      <view class="list-search-input">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input
            v-model="queryParams.configName"
            class="list-input"
            placeholder="搜索配置名称"
            @input="handleSearchInput"
            @confirm="handleSearch"
        />
        <uni-icons
            v-if="queryParams.configName"
            type="clear"
            size="16"
            color="#999"
            @click="handleClear">
        </uni-icons>
      </view>
      <view class="list-filter-btn" @click="toggleFilter">
        <uni-icons type="filter" size="14" color="#666"></uni-icons>
        <text>筛选</text>
      </view>
    </view>

    <!-- 高级筛选抽屉 -->
    <uni-popup ref="filterPopup" type="right" :mask-click="false">
      <view class="list-filter-drawer">
        <view class="list-filter-header">
          <text class="list-filter-title">高级筛选</text>
          <uni-icons type="close" size="20" @click="closeFilter"></uni-icons>
        </view>

        <view class="list-filter-content">
          <view class="list-filter-item">
            <text class="list-filter-label">存储类型</text>
            <BottomSelect
                v-model="queryParams.storageType"
                :options="storageTypeOptions"
                value-field="value"
                label-field="text"
                placeholder="请选择存储类型"
                title="选择存储类型"/>
          </view>

          <view class="list-filter-item">
            <text class="list-filter-label">状态</text>
            <BottomSelect
                v-model="queryParams.status"
                :options="statusOptions"
                value-field="value"
                label-field="text"
                placeholder="请选择状态"
                title="选择状态"/>
          </view>
        </view>

        <view class="list-filter-footer">
          <view class="btn btn-reset" @click="handleFilterReset">重置</view>
          <view class="btn btn-confirm" @click="handleFilterConfirm">确定</view>
        </view>
      </view>
    </uni-popup>

    <!-- 操作按钮栏 -->
    <view class="list-action-bar">
      <view class="btn btn-primary" @click="handleAdd" v-if="checkPermission(['file:storage:add'])">
        <uni-icons type="plus" size="14" color="#007aff"></uni-icons>
        <text>新增</text>
      </view>
      <view class="btn btn-default" @click="handleRefresh">
        <uni-icons type="reload" size="14" color="#666"></uni-icons>
        <text>刷新</text>
      </view>
    </view>

    <!-- 存储配置列表 -->
    <view class="list-content">
      <view
          v-for="config in storageList"
          :key="config.configId"
          class="list-item"
          @click="handleView(config)">

        <view class="list-avatar">
          <view class="storage-icon" :class="getStorageTypeClass(config.storageType)">
            <uni-icons :type="getStorageTypeIcon(config.storageType)" size="24" color="#fff"></uni-icons>
          </view>
        </view>

        <view class="list-info">
          <view class="list-header">
            <text class="list-title">{{ config.configName }}</text>
            <view class="status-badge" :class="config.status == 1 ? 'status-normal' : 'status-disabled'">
              {{ config.status == 1 ? '启用' : '停用' }}
            </view>
            <view v-if="config.isDefault === 1" class="default-badge">
              默认
            </view>
          </view>

          <view class="list-details">
            <view class="detail-item">
              <uni-icons type="cloud" size="14" color="#999"></uni-icons>
              <text class="detail-text">{{ getStorageTypeName(config.storageType) }}</text>
            </view>

            <view class="detail-item" v-if="config.endpoint">
              <uni-icons type="location" size="14" color="#999"></uni-icons>
              <text class="detail-text">{{ config.endpoint }}</text>
            </view>

            <view class="detail-item" v-if="config.bucketName">
              <uni-icons type="folder" size="14" color="#999"></uni-icons>
              <text class="detail-text">{{ config.bucketName }}</text>
            </view>

            <view class="detail-item">
              <uni-icons type="star" size="14" color="#999"></uni-icons>
              <text class="detail-text">{{ config.enableDirectUpload === 1 ? '支持直传' : '不支持直传' }}</text>
            </view>
          </view>
        </view>

        <view class="list-actions">
          <view class="action-btn action-primary" @click.stop="handleEdit(config)"
                v-if="checkPermission(['file:storage:edit'])">
            <uni-icons type="compose" size="14" color="#007aff"></uni-icons>
            <text class="action-text">编辑</text>
          </view>
          <view
              class="action-btn action-warning"
              @click.stop="handleTest(config)"
              v-if="config.storageType !== 'local' && checkPermission(['file:storage:test'])">
            <uni-icons type="refresh" size="14" color="#ff9500"></uni-icons>
            <text class="action-text">测试</text>
          </view>
          <view
              class="action-btn"
              :class="config.status == 1 ? 'action-warning' : 'action-success'"
              @click.stop="handleStatusChange(config)"
              v-if="checkPermission(['file:storage:edit'])">
            <uni-icons :type="config.status == 1 ? 'close' : 'checkmarkempty'" size="14"
                       :color="config.status == 1 ? '#ff9500' : '#34c759'"></uni-icons>
            <text class="action-text">{{ config.status == 1 ? '停用' : '启用' }}</text>
          </view>
          <view
              class="action-btn action-info"
              @click.stop="handleSetDefault(config)"
              v-if="config.status == 1 && config.isDefault !== 1 && checkPermission(['file:storage:edit'])">
            <uni-icons type="star" size="14" color="#007aff"></uni-icons>
            <text class="action-text">默认</text>
          </view>
          <view class="action-btn action-danger" @click.stop="handleDelete(config)"
                v-if="config.storageType !== 'local' && checkPermission(['file:storage:remove'])">
            <uni-icons type="trash" size="14" color="#ff3b30"></uni-icons>
            <text class="action-text">删除</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view v-if="storageList.length > 0" class="list-load-more">
      <uni-load-more
          :status="loadStatus"
          :content-text="loadText"
          @clickLoadMore="handleLoadMore">
      </uni-load-more>
    </view>

    <!-- 空状态 -->
    <view v-if="!loading && storageList.length === 0" class="list-empty">
      <uni-icons type="cloud" size="48" color="#ddd"></uni-icons>
      <text class="list-empty-text">暂无存储配置</text>
      <button class="btn btn-primary" @click="handleAdd" v-if="checkPermission(['file:storage:add'])">添加配置</button>
    </view>
  </view>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {
  changeStorageConfigStatus,
  delStorageConfig,
  listStorageConfig,
  setDefaultStorageConfig,
  testStorageConfig
} from '@/api/filemanager/storage'
import {BottomSelect} from '@/components/select'
import {usePermission} from '@/utils/permission'
import {useFileConfigStore} from '@/store/modules/fileConfig'

const {proxy} = getCurrentInstance()
const checkPermission = usePermission()
const fileConfigStore = useFileConfigStore()

// 数据定义
const storageList = ref([])
const total = ref(0)
const loading = ref(false)
const loadStatus = ref('more')
const filterPopup = ref(null)

const loadText = reactive({
  contentdown: '上拉显示更多',
  contentrefresh: '正在加载...',
  contentnomore: '没有更多数据了'
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  configName: '',
  storageType: '',
  status: ''
})

// 存储类型选项
const storageTypeOptions = [
  {value: '', text: '全部类型'},
  {value: 'local', text: '本地存储'},
  {value: 'minio', text: 'MinIO'},
  {value: 'aliyun', text: '阿里云OSS'},
  {value: 'tencent', text: '腾讯云COS'},
  {value: 'aws', text: 'AWS S3'}
]

// 状态选项
const statusOptions = [
  {value: '', text: '全部状态'},
  {value: '1', text: '启用'},
  {value: '0', text: '停用'}
]

// 页面加载
onMounted(() => {
  getList()
})

// 获取存储配置列表
async function getList() {
  if (loading.value) return

  loading.value = true
  loadStatus.value = 'loading'

  try {
    const response = await listStorageConfig(queryParams)
    if (response.code === 200) {
      const newData = response.rows || []

      if (queryParams.pageNum === 1) {
        storageList.value = newData
      } else {
        storageList.value.push(...newData)
      }

      total.value = response.total || 0

      if (storageList.value.length >= total.value) {
        loadStatus.value = 'noMore'
      } else {
        loadStatus.value = 'more'
      }
    }
  } catch (error) {
    console.error('获取存储配置列表失败:', error)
    proxy.$modal.showToast('获取存储配置列表失败')
    loadStatus.value = 'more'
  } finally {
    loading.value = false
  }
}

// 获取存储类型名称
function getStorageTypeName(type) {
  const typeMap = {
    'local': '本地存储',
    'minio': 'MinIO',
    'aliyun': '阿里云OSS',
    'tencent': '腾讯云COS',
    'aws': 'AWS S3'
  }
  return typeMap[type] || type
}

// 获取存储类型图标
function getStorageTypeIcon(type) {
  const iconMap = {
    'local': 'home',
    'minio': 'cloud',
    'aliyun': 'cloud-upload',
    'tencent': 'cloud-download',
    'aws': 'cloud'
  }
  return iconMap[type] || 'cloud'
}

// 获取存储类型样式类
function getStorageTypeClass(type) {
  const classMap = {
    'local': 'storage-local',
    'minio': 'storage-minio',
    'aliyun': 'storage-aliyun',
    'tencent': 'storage-tencent',
    'aws': 'storage-aws'
  }
  return classMap[type] || 'storage-default'
}

// 事件处理
let searchTimer = null

function handleSearchInput() {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    handleQuery()
  }, 300)
}

function handleSearch() {
  handleQuery()
}

function handleClear() {
  queryParams.configName = ''
  handleQuery()
}

function toggleFilter() {
  filterPopup.value.open()
}

function closeFilter() {
  filterPopup.value.close()
}

function handleFilterConfirm() {
  closeFilter()
  handleQuery()
}

function handleFilterReset() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    configName: '',
    storageType: '',
    status: ''
  })
}

function handleLoadMore() {
  if (loadStatus.value === 'more') {
    queryParams.pageNum++
    getList()
  }
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  storageList.value = []
  getList()
}

// 业务操作方法
function handleAdd() {
  uni.navigateTo({
    url: './edit?mode=add'
  })
}

function handleEdit(config) {
  uni.navigateTo({
    url: `./edit?mode=edit&configId=${config.configId}`
  })
}

function handleView(config) {
  uni.navigateTo({
    url: `./edit?mode=view&configId=${config.configId}`
  })
}

async function handleStatusChange(config) {
  try {
    const newStatus = config.status == 1 ? 0 : 1
    const statusText = newStatus == 1 ? '启用' : '停用'

    await proxy.$modal.confirm(`确认要${statusText}存储配置"${config.configName}"吗？`)

    const response = await changeStorageConfigStatus({
      configId: config.configId,
      status: newStatus
    })
    if (response.code === 200) {
      config.status = newStatus
      // 更新缓存中的配置状态
      fileConfigStore.updateConfig({configId: config.configId, status: newStatus})
      proxy.$modal.showToast(`${statusText}成功`)
    }
  } catch (error) {
    console.error('修改状态失败:', error)
  }
}

async function handleTest(config) {
  try {
    proxy.$modal.showLoading('正在测试连接...')

    const response = await testStorageConfig(config)
    if (response.code === 200) {
      proxy.$modal.hideLoading()
      proxy.$modal.showToast('连接测试成功')
    }
  } catch (error) {
    proxy.$modal.hideLoading()
    console.error('测试连接失败:', error)
    proxy.$modal.showToast('连接测试失败')
  }
}

async function handleDelete(config) {
  try {
    await proxy.$modal.confirm(`确认要删除存储配置"${config.configName}"吗？`)

    const response = await delStorageConfig(config.configId)
    if (response.code === 200) {
      // 从缓存中删除配置
      fileConfigStore.removeConfig(config.configId)
      proxy.$modal.showToast('删除成功')
      handleQuery()
    }
  } catch (error) {
    console.error('删除存储配置失败:', error)
  }
}

async function handleSetDefault(config) {
  try {
    await proxy.$modal.confirm(`确认要将"${config.configName}"设为默认存储配置吗？`)

    // 如果不是本地存储，先测试连接
    if (config.storageType !== 'local') {
      proxy.$modal.showLoading('正在测试连接...')

      try {
        const testResponse = await testStorageConfig(config)
        if (testResponse.code !== 200) {
          proxy.$modal.hideLoading()
          proxy.$modal.showToast('连接测试失败，无法设为默认配置')
          return
        }
      } catch (testError) {
        proxy.$modal.hideLoading()
        console.error('测试连接失败:', testError)
        proxy.$modal.showToast('连接测试失败，无法设为默认配置')
        return
      }

      proxy.$modal.hideLoading()
    }

    // 连接测试通过，设置为默认配置
    const response = await setDefaultStorageConfig(config.configId)
    if (response.code === 200) {
      // 更新列表中的默认状态
      storageList.value.forEach(item => {
        item.isDefault = item.configId === config.configId ? 1 : 0
      })

      // 刷新缓存
      await fileConfigStore.refreshCache()
      proxy.$modal.showToast('设置默认配置成功')
    }
  } catch (error) {
    console.error('设置默认配置失败:', error)
    proxy.$modal.showToast('设置默认配置失败')
  }
}

function handleRefresh() {
  // 刷新时同时刷新缓存
  fileConfigStore.refreshCache()
  handleQuery()
}
</script>

<style lang="scss" scoped>
@import '@/styles/list-page.scss';

// 存储图标样式
.storage-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;

  &.storage-local {
    background: linear-gradient(135deg, #ff6b6b, #ee5a24);
  }

  &.storage-minio {
    background: linear-gradient(135deg, #4834d4, #686de0);
  }

  &.storage-aliyun {
    background: linear-gradient(135deg, #ff9f43, #feca57);
  }

  &.storage-tencent {
    background: linear-gradient(135deg, #00d2d3, #01a3a4);
  }

  &.storage-aws {
    background: linear-gradient(135deg, #ff9500, #ff6348);
  }

  &.storage-default {
    background: linear-gradient(135deg, #a55eea, #8854d0);
  }
}

// 默认标识
.default-badge {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}
</style>
